package com.spark.netty.demo2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.*;

public class Server {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        EventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(8081)
                    .childHandler(new ChannelInitializer<Channel>() {

                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            // TODO Auto-generated method stub
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new IdleStateHandler(10, 0, 0));
                            pipeline.addLast(new MsgPckDecode());
                            pipeline.addLast(new MsgPckEncode());
                            pipeline.addLast(new ServerHandler());
                        }
                    });
            System.out.println("start server 8081 --");
            testSend();
            ChannelFuture sync = serverBootstrap.bind().sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅的关闭资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static void testSend() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Random random = new Random();
                Collection<Channel> channels = ServerHandler.channels.values();
                Channel channel = (Channel) channels.toArray()[random.nextInt(100) % channels.size()];
                if (channel != null) {
                    System.out.println(channel.id().asShortText() + "起床，");
                    channel.writeAndFlush(new Model(TypeData.CUSTOMER, "=========起床了==============")).addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) {
                            System.out.println(future.channel().id().asShortText() + "起来了，");
                        }
                    });
                }
            }
        }, 10 * 1000, 10 * 1000);
    }
}